import {
  GetInfoPicture,
  GetPaymentFunctionInfo,
  GetPreviewImage,
  PostDeleteData,
  PostInfoPicture,
  PostPaymentFunctionInfo
} from "/constData/requestFun/_httpRequest";
import isEmpty from 'loadsh/isEmpty'
import {
  POLICIES
} from '/constData/_';
import {
  GetContractManagement,
  GetContractManagementById,
  GetEvection,
  GetEvectionById,
  GetPayment,
  GetPaymentAccount,
  GetPaymentBanks,
  GetPaymentById,
  GetPaymentReceivingUnit,
  GetReimbursement,
  GetReimbursementById,
  PaymentDeleteData,
  PostPayment
} from "/constData/requestFun/_teseRequest";
import compact from 'loadsh/compact'
import {
  CORPID,
  SPACEID
} from '/constData/requestFun/_globalData';
Page({
  data: {
    approve: [],


    options: [{
        text: '测试费用',
        value: '测试费用',
        subText: '测试化验费、技术服务费、实验室耗材费等'
      },
      {
        text: '投资费用',
        value: '投资费用',
        subText: '投资款，包括股权投资、债权投资及委托贷款等'
      },
      {
        text: '融资支出',
        value: '融资支出',
        subText: '归还银行贷款本金、利息、融资服务费等'
      },
      {
        text: '日常费用',
        value: '日常费用',
        subText: '办公费、办公场所租赁费、日常维修费、物管费、水电气费、电话及上网费、植物租摆费等'
      },
      {
        text: '聘请中介机构费',
        value: '聘请中介机构费',
        subText: '法律顾问费、审计费、评估费、招聘费以及其他聘请中介机构费等'
      },
      {
        text: '汽车费',
        value: '汽车费',
        subText: '油费、维修保养费、保险费、停车费、洗车费、通行费等'
      },
      {
        text: '差旅费',
        value: '差旅费',
        subText: ' 长途交通费、住宿费、误餐费、出差公杂费等'
      },
      {
        text: '业务招待费',
        value: '业务招待费',
        subText: ''
      },
      {
        text: '会务费',
        value: '会务费',
        subText: ''
      },
      {
        text: '广告费、宣传费',
        value: '广告费、宣传费',
        subText: ''
      },
      {
        text: '咨询服务费',
        value: '咨询服务费',
        subText: ''
      },
      {
        text: '其他费用',
        value: '其他费用',
        subText: ''
      },
      {
        text: '项目资金',
        value: '项目资金',
        subText: ''
      }
    ],
    choose: [{
        value: '无内部关联合同',
        label: '无内部关联合同'
      },
      // {
      //   value: '出差',
      //   label: '出差'
      // },
      {
        value: '关联合同',
        label: '关联合同'
      },
      // {
      //   value: '报销',
      //   label: '报销'
      // },
    ],
    ChooseValue: '无',

    item: 1,
    min: new Date(),
    max: new Date('2033/12/02'),
    defaultDate: new Date(),
    paymentinfo: {
      CorpId: '', //申请人
      ContractNumber: '', //合同编号
      ReasonPayment: '', //付款事由
      PaymentType: '测试费用', //付款类型
      Amount: '', //金额
      LargeAmount: '', //大写
      PaymentMethods: '', //付款方式
      DatePayment: '', //支付日期
      PurchaseDetails: '', //采购明细
      ReceivingUnit: '', //收款单位名称
      Bank: '', //开户行
      Account: '', //银行账号
      PaymentInstructions: '', //付款说明
      SourcesFunding: '', //明确列出经费来源
      Invoicing: '', //供应商开票情况
      Annex: '[]', //付款合同扫描件
      Remark: '', //备注
      AssociateOtherType:'',
      AssociateOtherId: '[]',
    },
    ReceiveData: [],

    position: '',
    animation: true,
    basicVisible: false,
    closeVisible: false,
    TravelRelevancyData: [],
    TravelRelevancyDisplayData: [],
    ContractRelevancyData: [],
    ContractRelevancyDisplayData: [],
    ExpenseRelevancyData: [],
    UnitData: [
    ],//收款单位数据
    BankData: [
    ],//开户行数据
    AccountData: [
    ],//银行账号数据
    // ExpenseRelevancyDisplayData: [],
  },
  handleChange(value) {
    this.setData({
      paymentinfo: {
        ...this.data.paymentinfo,
        AssociateOtherType: value
      }
    })
    // console.log('eeee',this.data.paymentinfo.AssociateOtherType);
  },
  Delete(e) {
    const id = e.currentTarget.dataset.id
    PaymentDeleteData(id, (res) => {
      my.alert({
        title: '撤销成功',
      });
      //刷新数据
      this.setData({
        ReceiveData: this.data.ReceiveData.filter((it) => {
          return it.item1.id !== id
        })
      })
    }, (err) => {
      my.alert({
        title: '撤销失败',
      });
    })
  },

  selectorProjectTravel(e) {
    const data = e.target.dataset.data
    const newAssociateOtherIds = [
      ...JSON.parse(this.data.paymentinfo.AssociateOtherId || '[]'), // 将字符串转换为数组，如果为空则使用空数组  
      data.item1.id // 添加新的ID到数组中  
    ];
    this.setData({
      TravelRelevancyDisplayData: [...this.data.TravelRelevancyDisplayData, data],
      paymentinfo: {
        ...this.data.paymentinfo,
        AssociateOtherId: JSON.stringify(newAssociateOtherIds) // 将数组转换回字符串，以符合您当前的数据结构  
      }
    })
    my.alert({
      title: '添加成功',
    });
  },
  selectorProjectContract(e) {
    const data = e.target.dataset.data
    const newAssociateOtherIds = [
      ...JSON.parse(this.data.paymentinfo.AssociateOtherId || '[]'), // 将字符串转换为数组，如果为空则使用空数组  
      data.item1.id // 添加新的ID到数组中  
    ];
    this.setData({
      ContractRelevancyDisplayData: [...this.data.ContractRelevancyDisplayData, data],
      paymentinfo: {
        ...this.data.paymentinfo,
        AssociateOtherId: JSON.stringify(newAssociateOtherIds) // 将数组转换回字符串，以符合您当前的数据结构  
      }
    })
    my.alert({
      title: '添加成功',
    });
  },

  handlePopupClose() {
    this.setData({
      basicVisible: false,
      scrollVisible: false,
      closeVisible: false,
    });
  },
  handleShowClose() {
    this.setData({
      closeVisible: true
    });
  },
  handleShowBasic(e) {
    var position = e.target.dataset.position;
    const TypeChoose = e.target.dataset.ChooseValue;
    this.setData({
      position: position,
      basicVisible: true,
    });
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        if (TypeChoose === '关联合同') {
          GetContractManagement((res) => {
            const cacheData = res.data.map(it => {
              if (it.item1.corpId === storage.data.result.userid) {
                it.item1['displayPicture'] = JSON.parse(it.item1.picture)
                it.item1['displayApprovalAnnex'] = JSON.parse(it.item1.approvalAnnex)
                return it
              }
            })
            this.setData({
              ContractRelevancyData: compact(cacheData).reverse()
            })
          })
        }
      }
    })
  },
  onContractNumberChange(value) {
    this.setData({
      paymentinfo: {
        ...this.data.paymentinfo,
        ContractNumber: value
      }
    })
  },
  onRemarkChange(e) {
    this.setData({
      paymentinfo: {
        ...this.data.paymentinfo,
        Remark: e,
      }
    })
  },
  onInvoicingChange(e) {
    this.setData({
      paymentinfo: {
        ...this.data.paymentinfo,
        Invoicing: e,
      }
    })
  },
  onSourcesFundingChange(e) {
    this.setData({
      paymentinfo: {
        ...this.data.paymentinfo,
        SourcesFunding: e,
      }
    })
  },
  onPaymentInstructionsChange(e) {
    this.setData({
      paymentinfo: {
        ...this.data.paymentinfo,
        PaymentInstructions: e,
      }
    })
  },
  onAccountChange(e) {
    this.setData({
      paymentinfo: {
        ...this.data.paymentinfo,
        Account: e,
      }
    })
  },
  onBankChange(e) {
    this.setData({
      paymentinfo: {
        ...this.data.paymentinfo,
        Bank: e,
      }
    })
  },
  onReceivingUnitChange(val) {
    this.setData({
      paymentinfo: {
        ...this.data.paymentinfo,
        ReceivingUnit: val
      }
    })
  },
  onPurchaseDetailsChange(e) {
    this.setData({
      paymentinfo: {
        ...this.data.paymentinfo,
        PurchaseDetails: e,
      }
    })
  },
  handleOk(date, format, e) {
    this.setData({
      paymentinfo: {
        ...this.data.paymentinfo,
        DatePayment: date
      },
    })
  },

  onPaymentMethodsChange(e) {

    this.setData({
      paymentinfo: {
        ...this.data.paymentinfo,
        PaymentMethods: e,
      }
    })
  },
  onAmountChange(e) {
    this.setData({
      paymentinfo: {
        ...this.data.paymentinfo,
        Amount: e,
        LargeAmount: intToChinese(e)
      },
      approve: POLICIES.PAYMENT_POLICIES(this.data.paymentinfo.PaymentType, e)

    })
  },
  onPaymentTypeChange(e) {
    this.setData({
      paymentinfo: {
        ...this.data.paymentinfo,
        PaymentType: e
      }
    })
  },
  onReasonPaymentChange(e) {
    this.setData({
      paymentinfo: {
        ...this.data.paymentinfo,
        ReasonPayment: e
      }
    })
  },
  //获取数据
  onLoad() {
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        new Promise((resolve) => {
          GetPayment((res) => {
            const cacheData = res.data.map(it => {
              if (it.item1.corpId === storage.data.result.userid) {
                it.item1['displayAnnex'] = JSON.parse(it.item1.annex)
                return it;
              }
            });
            resolve(cacheData);
          });
        }).then((cacheData) => {
          const updatedResPromises = cacheData.map(it => {
            if (it.item1.associateOtherType === '关联合同') {
              const associateIds = (typeof it.item1.associateOtherId === 'string' && it.item1.associateOtherId === '[]') ? [] : JSON.parse(it.item1.associateOtherId);
              it.item3 = []
              if (it.item1.corpId === storage.data.result.userid && associateIds.length > 0) {
                return Promise.all(associateIds.map(associateId => {
                  return new Promise((resolve) => {
                    GetContractManagementById(associateId, (ContractRes) => {
                      it.item3.push(ContractRes.data.item1)
                      resolve(it);
                    });
                  });
                })).then(() => it); // 所有 Topic 获取完毕后返回当前对象  
              } else {
                // 如果 associateIds 为空或 it.item1.corpId 不匹配，则直接返回当前对象  
                return Promise.resolve(it);
              }
            }
            else {
              return Promise.resolve(it);
            }
          });
          // 等待所有 Promise 完成  
          return Promise.all(updatedResPromises).then(updatedRes => {
            this.setData({
              paymentinfo: {
                ...this.data.paymentinfo,
                CorpId: storage.data.result.userid
              },
              ReceiveData: compact(updatedRes).reverse()
            });
            console.log('ReceiveData', this.data.ReceiveData);
          });
        });
        
      }
    });

    GetPaymentReceivingUnit((res)=>{
      console.log('res',res);
      this.setData({
        UnitData: res.data
      })
    })
    GetPaymentBanks((res)=>{
      console.log('res2',res);
      this.setData({
        BankData: res.data
      })
    })
    GetPaymentAccount((res)=>{
      console.log('res3',res);
      this.setData({
        AccountData: res.data
      })
    })
  },
  // 上传数据
  onSubmit(e) {
    PostPayment(JSON.stringify(this.data.paymentinfo),
      (res) => {
        my.alert({
          title: '提交成功',
        });
        my.getStorage({
          key: 'userInfo',
          success: (storage) => {
            new Promise((resolve) => {
              GetPayment((res) => {
                
                const cacheData = res.data.map(it => {
                  if (it.item1.corpId === storage.data.result.userid) {
                    it.item1['displayAnnex'] = JSON.parse(it.item1.annex)
                    return it;
                  }
                });
                resolve(cacheData);
              });
            }).then((cacheData) => {
              const updatedResPromises = cacheData.map(it => {
                if (it.item1.associateOtherType === '关联合同') {
                  const associateIds = (typeof it.item1.associateOtherId === 'string' && it.item1.associateOtherId === '[]') ? [] : JSON.parse(it.item1.associateOtherId);
                  it.item3 = []
                  if (it.item1.corpId === storage.data.result.userid && associateIds.length > 0) {
                    return Promise.all(associateIds.map(associateId => {
                      return new Promise((resolve) => {
                        GetContractManagementById(associateId, (ContractRes) => {
                          it.item3.push(ContractRes.data.item1)
                          resolve(it);
                        });
                      });
                    })).then(() => it); // 所有 Topic 获取完毕后返回当前对象  
                  } else {
                    // 如果 associateIds 为空或 it.item1.corpId 不匹配，则直接返回当前对象  
                    return Promise.resolve(it);
                  }
                }
                else {
                  return Promise.resolve(it);
                }
    
              });
              // 等待所有 Promise 完成  
              return Promise.all(updatedResPromises).then(updatedRes => {
                this.setData({
                  paymentinfo: {
                    ...this.data.paymentinfo,
                    CorpId: storage.data.result.userid
                  },
                  ReceiveData: compact(updatedRes).reverse()
                });
              });
            });
          }
        });
        this.setData({
          paymentinfo: {
            ...this.data.paymentinfo,
            ReasonPayment: '', //付款事由
            PaymentType: '测试费用', //付款类型
            Amount: '', //金额
            LargeAmount: '', //大写
            PaymentMethods: '', //付款方式
            DatePayment: '', //支付日期
            PurchaseDetails: '', //采购明细
            ReceivingUnit: '', //收款单位名称
            Bank: '', //开户行
            Account: '', //银行账号
            PaymentInstructions: '', //付款说明
            SourcesFunding: '', //明确列出经费来源
            Invoicing: '', //供应商开票情况
            // Picture: [],//发票照片
            Annex: '[]', //付款合同扫描件
            Remark: '', //备注
          }
        })
      },
      (err) => {
        my.alert({
          title: '提交成功1',
        });
      })
  },


  //上传文件
  onUpload() {
    let imageAnnex = ''
    dd.uploadAttachmentToDingTalk({
      image: {
        max: 9,
        spaceId: SPACEID,
        compress: true,
        folderId: '',
        multiple: true,
      },
      file: {
        spaceId: SPACEID,
        max: 9,
        folderId: ''
      },
      types: ['photo', 'file'],
      success: (res) => {
        const srcAnnex = this.data.paymentinfo.Annex
        imageAnnex = res.data
        imageAnnex.push(...JSON.parse(srcAnnex))
        this.setData({
          displaydata: imageAnnex,
          paymentinfo: {
            ...this.data.paymentinfo,
            Annex: JSON.stringify(imageAnnex)
          }
        })
      },
      fail: () => {},
      complete: () => {},
    });
  },
  PreviewBtn(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },
  CheckPictures(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },
});

function intToChinese(money) {
  //汉字的数字
  var cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  //基本单位
  var cnIntRadice = ['', '拾', '佰', '仟'];
  //对应整数部分扩展单位
  var cnIntUnits = ['', '万', '亿', '兆'];
  //对应小数部分单位
  var cnDecUnits = ['角', '分', '毫', '厘'];
  //整数金额时后面跟的字符
  var cnInteger = '整';
  //整型完以后的单位
  var cnIntLast = '元';
  //最大处理的数字
  var maxNum = 999999999999999.9999;
  //金额整数部分
  var integerNum;
  //金额小数部分
  var decimalNum;
  //输出的中文金额字符串
  var chineseStr = '';
  //分离金额后用的数组，预定义
  var parts;
  if (money === '') { //不能用==
    return '';
  }
  money = parseFloat(money);
  if (money >= maxNum) {
    //超出最大处理数字
    return '';
  }
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger;
    return chineseStr;
  }
  //转换为字符串
  money = money.toString();
  if (money.indexOf('.') == -1) {
    integerNum = money;
    decimalNum = '';
  } else {
    parts = money.split('.');
    integerNum = parts[0];
    decimalNum = parts[1].substr(0, 4);
  }
  //获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    var zeroCount = 0;
    var IntLen = integerNum.length;
    for (var i = 0; i < IntLen; i++) {
      var n = integerNum.substr(i, 1);
      var p = IntLen - i - 1;
      var q = p / 4;
      var m = p % 4;
      if (n == '0') {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        //归零
        zeroCount = 0;
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    chineseStr += cnIntLast;
  }
  //小数部分
  if (decimalNum != '') {
    var decLen = decimalNum.length;
    for (var i = 0; i < decLen; i++) {
      var n = decimalNum.substr(i, 1);
      if (n != '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (chineseStr == '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (decimalNum == '') {
    chineseStr += cnInteger;
  }
  return chineseStr;
}